<template>
	<view class="container">
		<view class="title">Anther Emergence Rate History</view>

		<!-- 编辑按钮 -->
		<view class="buts">
			<view class="edit-button" @click="toggleEdit">
				{{ isEditing ? 'Edit Finish' : 'Edit' }}
			</view>
			<view class="back-button" @click="navigatorback">
				back
			</view>
		</view>

		<!-- Action Buttons -->
		<view class="action-buttons" v-if="isEditing">
			<view class="popup-button" @click="cancelEdit">Cancel</view>
			<view class="popup-button" @click="toggleSelectAll">{{ allSelected ? 'Deselect All' : 'Select All' }}</view>
			<view class="popup-button" @click="exportSelected">Export</view>
			<view class="popup-button" @click="deleteSelected">Delete</view>
		</view>
		<div v-if="isLoading" class="loading-indicator">
			The history is being obtained...
		</div>
		<!-- Canvas for Exporting -->
		<canvas class="canvas"
			:style="{ margin: '30rpx', height: heights + 'px', position: 'absolute', left: '-9999px' }"
			canvas-id="myCanvas" ref="myCanvas" willReadFrequently="true"></canvas>


		<view class="content" v-for="(response, index) in sortedResponses" :key="index">
			<text class="time-title">{{ response.uploadTime }}</text>
			<checkbox-group @change="(event) => handleCheckboxChange(event, index)">
				<view v-for="(result, resIndex) in response.allResult" :key="resIndex" class="result-item">
					<checkbox :value="result.id" :checked="result.selected" v-if="isEditing"></checkbox>
					<img :src="`data:image/jpeg;base64,${result.base64Image}`" class="result-image" />
					<view class="levels">
						<custom-table title="Anther Emergence" credibilityLabel="Credibility"
							:results="topThreeLevels(result.result)" resultField="level" percentageField="percentage" />
					</view>
					<view class="beizhu">
						<uni-easyinput type="textarea" v-model="result.remark"
							@blur="updateRemark(result.id, result.remark)" placeholder="Edit" />
					</view>
				</view>
			</checkbox-group>
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	computed,
	onMounted
} from 'vue';
import customTable from '@/components/customTable.vue';

const userId = ref(null);
const token = ref(null);
const responses = ref([]);
const isEditing = ref(false);
const selectedIds = ref([]);
const allSelected = ref(false);
const isLoading = ref(false);
const heights = ref(1000);
const navigatorback = () => {
	uni.navigateTo({
		url: '/pages/user/index',
	});
};
// 获取用户ID  
const getUserId = () => {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: 'user-data',
			success: (res) => {
				userId.value = res.data.userId;
				console.log('获取到的用户ID:', userId.value);
				resolve();
			},
			fail: reject,
		});
	});
};

// 获取令牌  
const getToken = () => {
	return new Promise((resolve, reject) => {
		uni.getStorage({
			key: 'user-data',
			success: (res) => {
				token.value = res.data.token;
				console.log('获取到的令牌:', token.value);
				resolve();
			},
			fail: reject,
		});
	});
};

// 调用API获取数据  
const fetchResponses = () => {
	isLoading.value = true;
	uni.request({
		url: `https://maize.ltd/yumi/find/sanfenAbility/${userId.value}`,
		method: 'POST',
		header: {
			'token': token.value,
		},
		success: (response) => {
			isLoading.value = false
			console.log('获取到的数据:', response.data);
			responses.value = response.data.data || []; // 更新数据  
		},
		fail: (error) => console.error('Error fetching data:', error),
		finally: () => isLoading.value = false, // 不管成功与否都设置加载状态为false  
	});
};

onMounted(() => {
	// 获取用户ID和令牌  
	Promise.all([getUserId(), getToken()])
		.then(() => fetchResponses())
		.catch(err => console.error('获取 ID 或令牌失败:', err));
});

// 更新备注  
const updateRemark = (id, remark) => {
	console.log('Updating remark', id);
	uni.request({
		url: `https://maize.ltd/yumi/sanfenAbility/remark`,
		method: 'PUT',
		data: {
			id,
			remark
		},
		header: {
			token: token.value
		},
		success: (res) => {
			if (res.data.code === 200) {
				uni.showToast({
					title: 'updated'
				})
			}
		},
		fail: (err) => {
			console.error('Failed to modify the remark request:', err);
			uni.showModal({
				title: 'Tip',
				content: 'Network error',
				showCancel: false,
				confirmText: 'OK'
			});
		}
	});
};

// 根据上传时间排序  
const sortedResponses = computed(() => {
	return Array.isArray(responses.value) ?
		responses.value.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime)) : [];
});

// 获取结实率和可信度数据  
const topThreeLevels = (result) => {
	const levels = [];
	for (let i = 0; i <= 5; i++) {
		let valueStr = result[`lu${i}`];
		if (valueStr.includes('E')) {
			valueStr = "0.0000000000001";
		}
		let value = parseFloat(valueStr);
		if (isNaN(value)) {
			// 如果解析结果为 NaN，则将其设为 0  
			value = 0;
		}

		levels.push({
			index: i,
			value
		});
	}

	return levels
		.sort((a, b) => b.value - a.value) // 按值降序排序  
		.slice(0, 3) // 取前 3 个  
		.map(({
			index,
			value
		}) => ({
			level: `lu ${index}`,
			percentage: (value * 100).toFixed(2) + '%' // 格式化为百分比  
		}));
};

// 切换编辑状态  
const toggleEdit = () => {
	isEditing.value = !isEditing.value;
	if (!isEditing.value) resetSelections();
};

const cancelEdit = () => {
	isEditing.value = !isEditing.value;
	if (!isEditing.value) {
		// 如果退出编辑模式，将所有结果重置为未选中状态  
		responses.value.forEach(response => {
			response.allResult.forEach(result => {
				result.selected = false;
			});
		});
		selectedIds.value = []; // 清空选中的 ID 数组  
	}
}

// 重置选中状态  
const resetSelections = () => {
	responses.value.forEach(response => {
		response.allResult.forEach(result => {
			result.selected = false;
		});
	});
	selectedIds.value = [];
};

// 处理选中项变化  
// 处理选中项变化  
const handleCheckboxChange = (event, index) => {

	if (event.detail.value.length) {

		selectedIds.value.push(index)
	} else {
		selectedIds.value = selectedIds.value.filter(id => id !== index)
	}

	console.log("选中的 ID:", selectedIds.value);
};

// 切换全选状态  
const toggleSelectAll = () => {
	allSelected.value = !allSelected.value;
	responses.value.forEach(response => {
		response.allResult.forEach(result => {
			result.selected = allSelected.value;
		});
	});
	selectedIds.value = allSelected.value ?
		responses.value.flatMap(response => response.allResult.map(result => result.id)) : [];
	console.log("全选状态:", allSelected.value, "选中的 ID:", selectedIds.value);
};

// 删除选中项  
const deleteSelected = () => {
	if (selectedIds.value.length === 0) return uni.showModal({
		title: 'Tip',
		content: 'Please Select first',
		showCancel: false,
		confirmText: 'OK'
	});

	uni.request({
		url: `https://maize.ltd/yumi/sanfenAbility/delete?ids=${selectedIds.value}`,
		method: 'DELETE',
		header: {
			token: token.value
		},
		success: (response) => {
			console.log('Deleted data:', response.data);
			responses.value = responses.value.map(response => ({
				...response,
				allResult: response.allResult.filter(result => !selectedIds.value.includes(
					result.id))
			})).filter(response => response.allResult.length > 0);
			resetSelections();
			uni.showModal({
				title: 'Tip',
				content: 'Delete successful',
				showCancel: false,
				confirmText: 'OK'
			})
		},
		fail: (error) => console.error('Error fetching data:', error),
	});
};

// 导出功能  
const export1 = () => {
	console.log('启动导出');
	let yOffset = 20;
	const selectedResults = responses.value.flatMap(response => response.allResult.filter(result => selectedIds
		.value.includes(result.id)));

	if (selectedResults.length === 0) {
		uni.showModal({
			title: 'Tip',
			content: 'select first',
			showCancel: false,
			confirmText: 'OK'
		});

		return;
	}

	heights.value = calculateCanvasHeight(selectedResults); // 计算 Canvas 高度  
	const ctx = uni.createCanvasContext('myCanvas', this, {
		willReadFrequently: true
	});

	yOffset = drawCanvasContent(ctx, selectedResults, yOffset);
	heights.value = yOffset; // 更新 heights 的值  

	// 导出 Canvas 为图片  
	ctx.draw(true, () => {
		uni.canvasToTempFilePath({
			x: 0,
			y: 0,
			width: 250,
			height: heights.value,
			canvasId: 'myCanvas',
			success: (res) => {
				console.log('导出的:', res);
				saveImageToLocal(res.tempFilePath);
			},
			fail: (err) => console.error('导出失败:', err),
		});
	});
};

// 计算 Canvas 高度  
const calculateCanvasHeight = (selectedResults) => {
	let totalHeight = 0;
	const uniqueUploadTimes = new Set();

	selectedResults.forEach(result => {
		const response = responses.value.find(r => r.allResult.some(res => res.id === result.id));
		if (response) {
			if (!uniqueUploadTimes.has(response.uploadTime)) {
				uniqueUploadTimes.add(response.uploadTime);
				totalHeight += 5 + 30 + 10; // 间隔和图片高度  
			}
			const levels = topThreeLevels(result.result);
			totalHeight += (levels.length * 20) + 10 + 30; // 结实率高度和备注高度  
		}
	});

	return totalHeight;
};

// 绘制 Canvas 内容  
const drawCanvasContent = (ctx, selectedResults, yOffset) => {
	const uniqueUploadTimes = new Set();

	selectedResults.forEach(result => {
		const response = responses.value.find(r => r.allResult.some(res => res.id === result.id));
		if (response && !uniqueUploadTimes.has(response.uploadTime)) {
			uniqueUploadTimes.add(response.uploadTime);
			ctx.fillText(response.uploadTime, 10, yOffset);
			yOffset += 5;

			response.allResult.forEach(result => {
				if (selectedIds.value.includes(result.id)) {
					ctx.drawImage(`data:image/jpeg;base64,${result.base64Image}`, 10, yOffset, 30,
						30);
					yOffset += 40;

					const levels = topThreeLevels(result.result);

					levels.forEach(level => {
						ctx.fillText(
							`Anther Emergence Rate: ${level.level}, Credibility: ${level.percentage}`,
							10,
							yOffset);
						yOffset += 20;
					});

					ctx.fillText(`Note: ${result.remark || 'Null'}`, 10, yOffset);
					yOffset += 30;
				}
			});
			yOffset += 10; // 每个响应的间隔  
		}
	});

	return yOffset;
};

// 保存图片到本地相册  
const saveImageToLocal = (tempFilePath) => {
	uni.saveImageToPhotosAlbum({
		filePath: tempFilePath,
		success: () =>
			uni.showModal({
				title: 'Tip',
				content: 'save successful',
				showCancel: false,
				confirmText: 'OK'
			}),
		fail: (err) => {
			console.error('Save failed:', err);
			uni.showModal({
				title: 'Tip',
				content: 'Save failed',
				showCancel: false,
				confirmText: 'OK'
			})
		}
	});
};

// 导出选中的项  
const exportSelected = () => {
	export1();
};
</script>

<style lang="less" scoped>
.container {
	padding-top: 140rpx;
	min-height: 100vh;
	position: relative;

	background-color: #e3f2e3; // 淡黄绿色背景  
	overflow: hidden;

	.title {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		font-weight: bold;
		color: #4CAF50; // 黄绿色主色调  
		margin-bottom: 50rpx;
	}

	.buts {
		display: flex;
		justify-content: space-around;
	}

	.edit-button {
		// position: absolute;
		// right: 20rpx;
		// top: 75rpx;
		// margin: 0 auto;
		color: white;
		background-color: #4CAF50; // 编辑按钮颜色  
		padding: 10rpx;
		border-radius: 5rpx;
		text-align: center;
		cursor: pointer;
		margin-bottom: 80rpx; // 与内容之间的间距  
		width: 140rpx; // 按钮宽度  
	}

	.back-button {
		// position: absolute;
		// right: 20rpx;
		// top: 75rpx;
		// margin: 0 auto;
		color: white;
		background-color: #4CAF50; // 编辑按钮颜色  
		padding: 10rpx;
		border-radius: 5rpx;
		text-align: center;
		cursor: pointer;
		margin-bottom: 80rpx; // 与内容之间的间距  
		width: 140rpx; // 按钮宽度  
	}

	.action-buttons {
		margin-bottom: 105rpx; // 与内容之间的间距 
		margin-left: 20rpx;
		display: flex;

		.popup-button {
			color: #4CAF50; // 按钮颜色  
			cursor: pointer;
			margin-right: 30rpx; // 按钮之间的间距  
		}
	}

	.content {
		margin-bottom: 20rpx;
		margin-left: 20rpx;
		width: auto;

		.time-title {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 10rpx;
		}

		.result-item {
			background-color: #ffffff;
			border: 1rpx solid #ddd;
			border-radius: 8rpx;
			padding: 5rpx 10rpx;
			box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.1);
			margin-bottom: 15rpx;
			display: flex;
			align-items: center;
			width: 95%;
			margin-right: 10rpx;

			.result-image {
				width: 170rpx; // 设置图片宽度  
				height: 170rpx; // 设置图片高度  
				object-fit: cover; // 保持纵横比并填充  
				border-radius: 8rpx;
				margin-right: 10rpx;
			}

			.levels {
				flex-grow: 1;
			}

			/* 表格样式已由customTable组件提供 */
			.beizhu {
				flex-shrink: 0;
				width: 150rpx;
				margin-left: 10rpx;
				::v-deep .uni-easyinput__content-textarea {
					height: 170rpx;
					margin: 0;
				}
			}
		}
	}

	.button {
		background-color: #4CAF50; // 操作按钮颜色  
		color: white;
		padding: 10rpx;
		border-radius: 5rpx;
		cursor: pointer;
	}
}
</style>